﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Auditing;
using Volo.Abp.Domain.Entities;

namespace My.Domain.Orders
{
    /// <summary>
    /// 订单，单元（聚合根）
    /// </summary>
    public class Order : BasicAggregateRoot<Guid>, IHasCreationTime
    {
        /// <summary>
        /// 订单号
        /// </summary>
        public string ReferenceNo { get; protected set; }

        /// <summary>
        /// 商品数量
        /// </summary>
        public int TotalItemCount { get; protected set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreationTime { get; protected set; }

        /// <summary>
        /// 订单明细
        /// </summary>
        public List<OrderLine> OrderLines { get; protected set; }

        /// <summary>
        /// 无参构造函数，反序列化
        /// </summary>
        private Order() { }

        public Order(Guid id, string referenceNo) : base(id)
        {
            Check.NotNull(referenceNo, nameof(referenceNo));

            ReferenceNo = referenceNo;

            OrderLines = new List<OrderLine>();
        }

        public void SetReferenceNo(string referenceNo)
        {
            ReferenceNo = referenceNo;
        }

        /// <summary>
        /// 添加订单明细
        /// </summary>
        public void AddOrderLine(Guid productId, int count)
        {
            if (count <= 0)
            {
                throw new ArgumentException("产品数量不能小于等于0", nameof(count));
            }
            var existingLine = OrderLines.FirstOrDefault(ol => ol.ProductId == productId);
            if (existingLine == null)
            {
                OrderLines.Add(new OrderLine(this.Id, productId, count));
            }
            else
            {
                existingLine.ChangeCount(count);
            }
            TotalItemCount += count;
        }
    }
}
